<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>轻量级NLP对话系统</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Microsoft YaHei', Arial, sans-serif;
            background: #FFFFFF;
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }

        .container {
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
            width: 100%;
            max-width: 1200px;
            height: 80vh;
            min-height: 600px;
            display: flex;
            overflow: hidden;
        }

        .chat-section {
            flex: 2;
            display: flex;
            flex-direction: column;
            border-right: 1px solid #e0e0e0;
        }

        .analysis-section {
            flex: 1;
            background: #f8f9fa;
            padding: 20px;
            overflow-y: auto;
        }

        .header {
            background: linear-gradient(135deg, #0682e6 0%, #4fa3f7 100%);
            color: #fff;
            padding: 20px;
            text-align: center;
        }

        .header h1 {
            font-size: 24px;
            margin-bottom: 5px;
        }

        .header p {
            opacity: 0.9;
            font-size: 14px;
        }

        .chat-container {
            flex: 1;
            padding: 20px;
            overflow-y: auto;
            background: #fafafa;
        }

        .message {
            margin-bottom: 20px;
            display: flex;
            animation: fadeIn 0.3s ease-in;
        }

        .message.user {
            justify-content: flex-end;
        }

        .message.bot {
            justify-content: flex-start;
        }

        .message-bubble {
            max-width: 70%;
            padding: 12px 18px;
            border-radius: 18px;
            word-wrap: break-word;
            line-height: 1.4;
            position: relative;
        }

        .message.user .message-bubble {
            background: linear-gradient(135deg, #0682e6 0%, #4fa3f7 100%);
            color: #fff;
        }

        .message.bot .message-bubble {
            background: white;
            color: #333;
            border: 1px solid #e0e0e0;
        }

        .message-time {
            font-size: 10px;
            opacity: 0.7;
            margin-top: 5px;
        }

        .input-container {
            padding: 20px;
            background: white;
            border-top: 1px solid #e0e0e0;
            display: flex;
            gap: 10px;
            align-items: center;
        }

        .message-input {
            flex: 1;
            padding: 12px 18px;
            border: 2px solid #e0e0e0;
            border-radius: 25px;
            outline: none;
            font-size: 14px;
            transition: border-color 0.3s;
        }

        .message-input:focus {
            border-color: #0682e6;
        }

        .send-button, .enhance-button {
            padding: 12px 20px;
            border: none;
            border-radius: 25px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.3s;
            font-weight: 500;
        }

        .send-button {
            background: linear-gradient(135deg, #0682e6 0%, #4fa3f7 100%);
            color: #fff;
        }

        .enhance-button {
            background: #28a745;
            color: white;
        }

        .send-button:hover, .enhance-button:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
        }

        .analysis-title {
            font-size: 18px;
            font-weight: 600;
            margin-bottom: 15px;
            color: #333;
            border-bottom: 2px solid #0682e6;
            padding-bottom: 5px;
        }

        .analysis-item {
            background: white;
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 15px;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
        }

        .analysis-item h4 {
            color: #0682e6;
            margin-bottom: 8px;
            font-size: 14px;
            font-weight: 600;
        }

        .analysis-content {
            font-size: 13px;
            color: #666;
            line-height: 1.4;
        }

        .keyword-tag {
            display: inline-block;
            background: #e6f1fd;
            color: #0682e6;
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 11px;
            margin: 2px;
        }

        .sentiment-positive {
            color: #28a745;
            font-weight: 600;
        }

        .sentiment-negative {
            color: #dc3545;
            font-weight: 600;
        }

        .sentiment-neutral {
            color: #6c757d;
            font-weight: 600;
        }

        .entity-tag {
            display: inline-block;
            padding: 3px 8px;
            border-radius: 10px;
            font-size: 11px;
            margin: 2px;
        }

        .entity-person { background: #ffe0e6; color: #d63384; }
        .entity-location { background: #e0f7fa; color: #00796b; }
        .entity-time { background: #fff3e0; color: #f57c00; }

        .controls {
            padding: 15px 20px;
            background: #f8f9fa;
            border-top: 1px solid #e0e0e0;
            display: flex;
            gap: 10px;
            justify-content: center;
        }

        .control-button {
            padding: 8px 16px;
            background: #6c757d;
            color: white;
            border: none;
            border-radius: 15px;
            cursor: pointer;
            font-size: 12px;
            transition: background 0.3s;
        }

        .control-button:hover {
            background: #545b62;
        }

        .loading {
            display: none;
            text-align: center;
            padding: 10px;
            color: #666;
        }

        .spinner {
            border: 2px solid #f3f3f3;
            border-top: 2px solid #0682e6;
            border-radius: 50%;
            width: 20px;
            height: 20px;
            animation: spin 1s linear infinite;
            display: inline-block;
            margin-right: 10px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .error-message {
            background: #f8d7da;
            color: #721c24;
            padding: 10px;
            border-radius: 5px;
            margin: 10px 0;
            border: 1px solid #f5c6cb;
        }

        @media (max-width: 768px) {
            .container {
                flex-direction: column;
                height: 90vh;
            }
            
            .analysis-section {
                border-right: none;
                border-top: 1px solid #e0e0e0;
                max-height: 30vh;
            }
            
            .chat-section {
                border-right: none;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- 聊天区域 -->
        <div class="chat-section">
            <div class="header">
                <h1>🤖 轻量级NLP对话系统</h1>
                <p>基于Python构建的智能对话机器人 | 用户: 哈桑和他的Python</p>
            </div>
            
            <div class="chat-container" id="chatContainer">
                <div class="message bot">
                    <div class="message-bubble">
                        <div>你好！我是你的AI助手，很高兴为你服务！我可以进行智能对话，还能分析你的语言特征哦~ 🎉</div>
                        <div class="message-time">2025-09-10 15:08:42</div>
                    </div>
                </div>
            </div>
            
            <div class="loading" id="loading">
                <div class="spinner"></div>正在处理中...
            </div>
            
            <div class="input-container">
                <input type="text" class="message-input" id="messageInput" 
                       placeholder="输入你的消息..." onkeypress="handleKeyPress(event)">
                <button class="send-button" onclick="sendMessage()">💬 发送</button>
                <button class="enhance-button" onclick="sendEnhancedMessage()">🔍 增强分析</button>
            </div>
            
            <div class="controls">
                <button class="control-button" onclick="showHistory()">📚 历史</button>
                <button class="control-button" onclick="clearChat()">🗑️ 清空</button>
                <button class="control-button" onclick="exportChat()">📤 导出</button>
                <button class="control-button" onclick="toggleAnalysis()">📊 分析面板</button>
            </div>
        </div>
        
        <!-- 分析区域 -->
        <div class="analysis-section" id="analysisSection">
            <div class="analysis-title">📊 NLP分析结果</div>
            <div id="analysisContent">
                <div class="analysis-item">
                    <h4>🔤 关键词提取</h4>
                    <div class="analysis-content" id="keywordsDisplay">
                        发送消息后显示关键词...
                    </div>
                </div>
                
                <div class="analysis-item">
                    <h4>💭 情感分析</h4>
                    <div class="analysis-content" id="sentimentDisplay">
                        发送消息后显示情感分析...
                    </div>
                </div>
                
                <div class="analysis-item">
                    <h4>🏷️ 命名实体识别</h4>
                    <div class="analysis-content" id="entitiesDisplay">
                        发送消息后显示实体识别...
                    </div>
                </div>
                
                <div class="analysis-item">
                    <h4>✂️ 中文分词</h4>
                    <div class="analysis-content" id="segmentationDisplay">
                        发送消息后显示分词结果...
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        let conversationHistory = [];
        let isEnhancedMode = false;

        // 添加消息到聊天界面
        function addMessage(message, isUser = false, timestamp = null) {
            const chatContainer = document.getElementById('chatContainer');
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${isUser ? 'user' : 'bot'}`;
            
            const bubbleDiv = document.createElement('div');
            bubbleDiv.className = 'message-bubble';
            
            const contentDiv = document.createElement('div');
            contentDiv.textContent = message;
            
            const timeDiv = document.createElement('div');
            timeDiv.className = 'message-time';
            timeDiv.textContent = timestamp || new Date().toLocaleString('zh-CN');
            
            bubbleDiv.appendChild(contentDiv);
            bubbleDiv.appendChild(timeDiv);
            messageDiv.appendChild(bubbleDiv);
            chatContainer.appendChild(messageDiv);
            
            chatContainer.scrollTop = chatContainer.scrollHeight;
        }

        // 显示加载状态
        function showLoading(show = true) {
            const loading = document.getElementById('loading');
            loading.style.display = show ? 'block' : 'none';
        }

        // 显示错误信息
        function showError(message) {
            const chatContainer = document.getElementById('chatContainer');
            const errorDiv = document.createElement('div');
            errorDiv.className = 'error-message';
            errorDiv.textContent = `❌ 错误: ${message}`;
            chatContainer.appendChild(errorDiv);
            chatContainer.scrollTop = chatContainer.scrollHeight;
        }

        // 发送普通消息
        async function sendMessage() {
            const input = document.getElementById('messageInput');
            const message = input.value.trim();
            
            if (!message) return;
            
            addMessage(message, true);
            input.value = '';
            showLoading(true);
            
            try {
                const response = await fetch('/chat', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ message: message })
                });
                
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}`);
                }
                
                const data = await response.json();
                showLoading(false);
                
                if (data.response) {
                    addMessage(data.response, false, data.timestamp);
                    conversationHistory.push({
                        user: message,
                        bot: data.response,
                        timestamp: data.timestamp
                    });
                } else {
                    showError('服务器响应格式错误');
                }
            } catch (error) {
                showLoading(false);
                console.error('Error:', error);
                showError('网络连接失败，请检查服务器状态');
            }
        }

        // 发送增强分析消息
        async function sendEnhancedMessage() {
            const input = document.getElementById('messageInput');
            const message = input.value.trim();
            
            if (!message) return;
            
            addMessage(message, true);
            input.value = '';
            showLoading(true);
            
            try {
                const response = await fetch('/enhanced_chat', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ message: message })
                });
                
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}`);
                }
                
                const data = await response.json();
                showLoading(false);
                
                if (data.response) {
                    addMessage(data.response, false);
                    updateAnalysisDisplay(data.analysis);
                    conversationHistory.push({
                        user: message,
                        bot: data.response,
                        analysis: data.analysis,
                        timestamp: new Date().toLocaleString('zh-CN')
                    });
                } else {
                    showError('服务器响应格式错误');
                }
            } catch (error) {
                showLoading(false);
                console.error('Error:', error);
                showError('网络连接失败，请检查服务器状态');
            }
        }

        // 更新分析显示
        function updateAnalysisDisplay(analysis) {
            // 更新关键词
            const keywordsDisplay = document.getElementById('keywordsDisplay');
            if (analysis.keywords && analysis.keywords.length > 0) {
                keywordsDisplay.innerHTML = analysis.keywords
                    .map(([word, count]) => `<span class="keyword-tag">${word} (${count})</span>`)
                    .join('');
            } else {
                keywordsDisplay.textContent = '未识别到关键词';
            }

            // 更新情感分析
            const sentimentDisplay = document.getElementById('sentimentDisplay');
            if (analysis.sentiment) {
                const sentiment = analysis.sentiment;
                const sentimentClass = `sentiment-${sentiment.sentiment}`;
                const sentimentText = {
                    'positive': '正面😊',
                    'negative': '负面😞',
                    'neutral': '中性😐'
                }[sentiment.sentiment] || '未知';
                
                sentimentDisplay.innerHTML = `
                    <span class="${sentimentClass}">${sentimentText}</span>
                    <br>置信度: ${(sentiment.score * 100).toFixed(1)}%
                    <br>正面词: ${sentiment.positive_count} | 负面词: ${sentiment.negative_count}
                `;
            } else {
                sentimentDisplay.textContent = '情感分析失败';
            }

            // 更新实体识别
            const entitiesDisplay = document.getElementById('entitiesDisplay');
            if (analysis.entities) {
                const entities = analysis.entities;
                let entitiesHtml = '';
                
                Object.entries(entities).forEach(([type, items]) => {
                    if (items && items.length > 0) {
                        const typeText = {
                            'person': '👤 人名',
                            'location': '📍 地点',
                            'time': '⏰ 时间',
                            'organization': '🏢 机构'
                        }[type] || type;
                        
                        entitiesHtml += `<div><strong>${typeText}:</strong> `;
                        entitiesHtml += items.map(item => 
                            `<span class="entity-tag entity-${type}">${item}</span>`
                        ).join('');
                        entitiesHtml += '</div>';
                    }
                });
                
                entitiesDisplay.innerHTML = entitiesHtml || '未识别到命名实体';
            } else {
                entitiesDisplay.textContent = '实体识别失败';
            }

            // 更新分词结果
            const segmentationDisplay = document.getElementById('segmentationDisplay');
            if (analysis.word_segmentation && analysis.word_segmentation.length > 0) {
                segmentationDisplay.innerHTML = analysis.word_segmentation
                    .map(word => `<span class="keyword-tag">${word}</span>`)
                    .join('');
            } else {
                segmentationDisplay.textContent = '分词失败';
            }
        }

        // 处理回车键
        function handleKeyPress(event) {
            if (event.key === 'Enter') {
                if (event.shiftKey) {
                    sendEnhancedMessage();
                } else {
                    sendMessage();
                }
            }
        }

        // 显示历史记录
        function showHistory() {
            if (conversationHistory.length === 0) {
                addMessage('📚 暂无对话历史记录', false);
                return;
            }
            
            let historyText = '📚 最近的对话记录:\n\n';
            conversationHistory.slice(-5).forEach((conv, index) => {
                historyText += `${index + 1}. [${conv.timestamp}]\n`;
                historyText += `👤 用户: ${conv.user}\n`;
                historyText += `🤖 助手: ${conv.bot}\n\n`;
            });
            
            addMessage(historyText, false);
        }

        // 清空聊天
        function clearChat() {
            if (confirm('确定要清空聊天记录吗？')) {
                document.getElementById('chatContainer').innerHTML = '';
                conversationHistory = [];
                
                // 重新添加欢迎消息
                addMessage('聊天记录已清空！我是你的AI助手，有什么可以帮助你的吗？', false);
                
                // 清空分析面板
                document.getElementById('keywordsDisplay').textContent = '发送消息后显示关键词...';
                document.getElementById('sentimentDisplay').textContent = '发送消息后显示情感分析...';
                document.getElementById('entitiesDisplay').textContent = '发送消息后显示实体识别...';
                document.getElementById('segmentationDisplay').textContent = '发送消息后显示分词结果...';
            }
        }

        // 导出聊天记录
        function exportChat() {
            if (conversationHistory.length === 0) {
                alert('没有对话记录可以导出');
                return;
            }
            
            const exportData = {
                user: '哈桑和他的Python',
                export_time: new Date().toISOString(),
                conversation_count: conversationHistory.length,
                conversations: conversationHistory
            };
            
            const blob = new Blob([JSON.stringify(exportData, null, 2)], {
                type: 'application/json'
            });
            
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `chat_history_${new Date().toISOString().slice(0, 10)}.json`;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
            
            addMessage('📤 聊天记录已导出到下载文件夹', false);
        }

        // 切换分析面板
        function toggleAnalysis() {
            const analysisSection = document.getElementById('analysisSection');
            const isHidden = analysisSection.style.display === 'none';
            
            analysisSection.style.display = isHidden ? 'block' : 'none';
            
            // 在移动端自动调整布局
            if (window.innerWidth <= 768) {
                const container = document.querySelector('.container');
                container.style.flexDirection = isHidden ? 'column' : 'column';
            }
        }

        // 页面加载完成后的初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 设置输入框焦点
            document.getElementById('messageInput').focus();
            
            // 检查服务器连接
            fetch('/health', { method: 'GET' })
                .then(response => {
                    if (!response.ok) {
                        showError('服务器连接失败，请检查后端服务是否启动');
                    }
                })
                .catch(error => {
                    showError('无法连接到服务器，请确保后端服务正在运行');
                });
        });

        // 响应式设计支持
        window.addEventListener('resize', function() {
            if (window.innerWidth <= 768) {
                document.querySelector('.container').style.flexDirection = 'column';
            } else {
                document.querySelector('.container').style.flexDirection = 'row';
            }
        });
    </script>
</body>
</html>